import React, {memo, useCallback, useEffect, useState} from 'react';
import {deleteArticle, getArticleList} from "@/network/article.request";
import {getArticleClassify} from "@/network/archives.request";
import {Button, Modal, Table} from 'antd';
import moment from "moment";
import {ArticleListWrapper} from "./style";
import AdminPagination from "@/components/admin-pagination";
import {withRouter} from "react-router";
import setMessage from "@/utils/setMessage";
import {filterClassifyList} from "@/utils/common";

function ArticleList(props) {
  const {userId, history} = props;

  const [offset, setOffset] = useState(0);
  const [limit] = useState(10);
  const [current, setCurrent] = useState(1);
  const [articleList, setArticleList] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalText, setModalText] = useState("");
  const [articleId, setArticleId] = useState();
  const [classifyList, setClassifyList] = useState([]);


  const changeArticleList = (userId, offset, limit) => {
    setIsLoading(true);
    getArticleList(userId, offset, limit).then(res => {
      setArticleList(res);
      setIsLoading(false);
    }).catch(console.log)
  }

  useEffect(() => {
    changeArticleList(userId, offset, limit);
    getArticleClassify(userId).then(res => {
      setClassifyList(filterClassifyList(res));
    }).catch(console.log)
  }, [userId, offset, limit])

  const handleUpdate = useCallback((record) => {
    const a_id = record.key;
    history.push(`/admin/add_article/u/${userId}/${a_id}`);
<<<<<<< HEAD
  }, [history, userId])
=======
  }, [history])
>>>>>>> 55285bfa6ef4017c5ce84e99c80d4e3e8747d5b9

  // 删除文章
  const handleOk = useCallback(() => {
    setConfirmLoading(true)
    deleteArticle(articleId).then(res => {
      if (res.affectedRows) {
        setMessage("删除文章成功", "success")
        changeArticleList(userId, offset, limit)
      } else {
        setMessage("删除文章失败", "error");
      }
      setConfirmLoading(false)
      setVisible(false);
    }).catch(error => {
      setMessage("删除文章失败", "error");
      setVisible(false);
      setConfirmLoading(false)
      console.log(error);
    })
  }, [articleId, userId, offset, limit])

  const handleDelete = useCallback((record) => {
    setModalText(`确定删除文章 ${record.title}`)
    setArticleId(record.key)
    setVisible(true);
  }, [])

  const columns = [
    {
      title: "id",
      dataIndex: "key",
      key: "key",
      align: "center",
      sorter: (a, b) => a.key - b.key,
      sortDirections: ["descend", "ascend"],
      width: 120,
      ellipsis: true
    },
    {
      title: "文章标题",
      dataIndex: "title",
      key: "title",
      align: "center",
      width: 260,
      ellipsis: true
    },
    {
      title: "字数",
      dataIndex: "count",
      key: "count",
      align: "center",
      sorter: (a, b) => a.count - b.count,
      sortDirections: ["descend", "ascend"]
    },
    {
      title: "阅读量",
      dataIndex: "viewCount",
      key: "viewCount",
      align: "center",
      sorter: (a, b) => a.viewCount - b.viewCount,
      sortDirections: ["descend", "ascend"]
    },
    {
      title: "归档",
      dataIndex: "classifyName",
      key: "classifyName",
      align: "center",
      filters: classifyList,
      onFilter: (value, record) => value === record.classifyName
    },
    {
      title: "发布时间",
      dataIndex: "createTime",
      key: "createTime",
      align: "center",
      sorter: (a, b) => Date.parse(a.createTime) - Date.parse(b.createTime),
      sortDirections: ["descend", "ascend"],
      render: (value) => (<>
        <span>
          {moment(value).format("YYYY-MM-DD HH:mm:ss")}
        </span>
      </>)
    },
    {
      title: "操作",
      dataIndex: "todo",
      key: 'todo',
      align: "center",
      render: (text, record) => (<>
        <Button onClick={e => handleUpdate(record)} type="primary" size="small" className="mr-2">修改</Button>
        <Button onClick={e => handleDelete(record)} type="primary" size="small" danger>删除</Button>
      </>)
    }
  ];

  const handleChange = useCallback((page, pageSize) => {
    setOffset((page - 1) * limit)
    setCurrent(page)
  }, [limit])

  return (
    <ArticleListWrapper>
      {
        articleList && articleList.length > 0 && (
          <>
            <Table
              pagination={false}
              columns={columns}
              dataSource={articleList}
              size="middle"
              loading={isLoading}
            />
            <AdminPagination
              total={Number(articleList[0].total)}
              current={current}
              defaultPageSize={limit}
              handleChange={handleChange}
            />
            <Modal
              title="删除操作"
              visible={visible}
              onOk={handleOk}
              cancelText="取消"
              okText="确定"
              confirmLoading={confirmLoading}
              onCancel={e => setVisible(false)}
            >
              <p>{modalText}</p>
            </Modal>
          </>
        )
      }
    </ArticleListWrapper>
  )
}

export default memo(withRouter(ArticleList))
